package part15工具包.作业;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
/**
 * [根据用户输入的年和月打印这个月的日历]
 * 从控制台输入一个指定日期时间格式的字符串(2019-09),然后根据用户的输入日期,打印该月的月历出来; 
 * @author DEGE
 *
 */
public class Homework_伟德 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入年份和月份：(格式yyyy-MM)");
		String strDate = scanner.nextLine();
		Date date = Homework_伟德.stringToDate(strDate);//调用本类静态方法，将输入字符串转为Date类型
		Homework_伟德.printCalendar(date);
		scanner.close();
	}
	
	//String转Date类型方法
	public static Date stringToDate(String strDate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Date date = null;
		try {
			date = sdf.parse(strDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}
	
	//打印月历方法
	public static void printCalendar(Date date) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date);
		int year = cal1.get(Calendar.YEAR);
		int month = cal1.get(Calendar.MONTH)+1;//第几个月
		cal1.set(Calendar.DAY_OF_MONTH, 1);//设置日期为1号
		int lastDay = cal1.getActualMaximum(Calendar.DAY_OF_MONTH);//获取该月的最后一天，即该月的总天数
		
		Calendar cal2 = Calendar.getInstance();
		cal2.set(Calendar.YEAR, year);
		cal2.set(Calendar.MONTH, month-2);//本月为month-1,上个月为month-2
		int lastDay1 = cal2.getActualMaximum(Calendar.DAY_OF_MONTH);//上个月的最后一天
		int day = lastDay1-cal1.get(Calendar.DAY_OF_WEEK)+2;//第一周从上个月几号开始
		
		System.out.println(year + "年" + month + "月");
		System.out.println("日"+"\t"+"一"+"\t"+"二"+"\t"+"三"+"\t"+"四"+"\t"+"五"+"\t"+"六"+"\t");
		//打印本周属于上个月的前几天，
		for (int i = 1; i < cal1.get(Calendar.DAY_OF_WEEK); i++) {
			System.out.print(day + "\t");
			day++;
		}
		//打印本月月历
		for (int i = 1; i <= lastDay; i++) {
			System.out.print(i + "\t");
			//控制到周六换行
			if ((cal1.get(Calendar.DAY_OF_WEEK)+i-1)%7 == 0) {
				System.out.println();
			}
		}
		
	}
}
